<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三数之和动画演示</title>
    <style>
        /* 响应式布局 */
        body {
            font-family: Arial, sans-serif;
            padding: 10px;
            max-width: 100%;
            margin: 0 auto;
            overflow-x: hidden;
        }
        .container {
            position: relative;
            height: 30vh; /* 适配手机屏幕 */
            margin: 20px 0;
            border: 1px solid #ddd;
            padding: 5px;
        }
        .bar {
            position: absolute;
            bottom: 0;
            width: calc(100% / 15); /* 自适应宽度 */
            background: #b3d9ff;
            transition: all 0.3s;
            text-align: center;
            font-size: 12px;
        }
        /* 指针样式 */
        .pointer {
            position: absolute;
            bottom: 0;
            width: 3px;
            height: 100%;
            background: red;
            transition: all 0.3s;
        }
        .pointer::after {
            content: attr(data-label);
            position: absolute;
            top: -20px;
            left: -15px;
            font-size: 10px;
            white-space: nowrap;
        }
        #i-pointer { background: #ff4444; }
        #j-pointer { background: #44ff44; }
        #k-pointer { background: #4444ff; }
        /* 移动端优化 */
        .status {
            padding: 5px;
            background: #f0f0f0;
            font-size: 14px;
            margin: 10px 0;
        }
        #solutions {
            padding: 5px;
            border: 1px solid #ddd;
            font-size: 12px;
        }
        /*button {*/
        /*    padding: 8px 15px;*/
        /*    margin: 5px;*/
        /*    font-size: 14px;*/
        /*}*/
        button {
    position: relative;
    padding: 16px 36px;
    margin: 12px;
    border: none;
    border-radius: 12px;
    font-family: 'Arial', sans-serif;
    font-size: 18px;
    font-weight: 700;
    color: #ffffff;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    overflow: hidden;
    outline: none;
    min-width: 160px;
            background-color: rgba(0,0,0,0.8);
}

    </style>



</head>
<body>
    <h2 style="color: cadetblue; text-align: center">开启埃及金字塔宝藏之门</h2>
    <div class="container" id="chart"></div>
    <div class="status" id="status">准备开始...</div>
    <div id="solutions" style="margin: 0 5%">
        <h3>找到的解 (<span id="count">0</span> 个):</h3>
        <ul id="solution-list"></ul>
    </div>
    <div style="text-align: center; margin: 20px 0">
        <button onclick="start()">开始演示</button>
        <button onclick="togglePause()">暂停</button>
        <button onclick="location.reload()">重置</button>
    </div>

<script>
// 初始数据
let isPaused = false; // 新增暂停状态标志
let currentPromise = null; // 用于控制暂停/继续的Promise

// 初始数据（保持不变）
const nums = [-1, 0, 1, 2, -1, -4, -2, 3, 0].sort((a,b) => a-b);
let solutions = [];
let animationSpeed = 1500;

// 新增函数：暂停/继续切换
// 新增函数：暂停/继续切换
function togglePause() {
    isPaused = !isPaused;
    const btn = document.querySelector("button[onclick='togglePause()']");
    btn.textContent = isPaused ? "继续" : "暂停";
}

async function runSteps() {
    for(let i = 0; i < nums.length - 2; i++) {
        if(i > 0 && nums[i] === nums[i-1]) continue;

        updateStatus(`正在检查 i=${i} (值: ${nums[i]})`);
        updatePointers(i, i+1, nums.length-1);
        await delay();

        let j = i+1, k = nums.length-1;
        while(j < k) {
            // 新增：每次循环前检查暂停
            await handlePause();

            updateStatus(`检查组合: [${nums[i]}, ${nums[j]}, ${nums[k]}]`);
            await delay();

            const sum = nums[i] + nums[j] + nums[k];
            if(sum === 0) {
                solutions.push([nums[i], nums[j], nums[k]]);
                showSolution([nums[i], nums[j], nums[k]]);
                highlightBars(i, j, k);
                document.getElementById('status').textContent = `🎉找到解: ${JSON.stringify([nums[i], nums[j], nums[k]])}`;

                do { j++; } while(j < k && nums[j] === nums[j-1]);
                do { k--; } while(j < k && nums[k] === nums[k+1]);
            } else if(sum > 0) {
                k--;
            } else {
                j++;
            }
            updatePointers(i, j, k);
            await delay();
        }
    }
    updateStatus("演示完成！");
}

// 新增函数：处理暂停逻辑
async function handlePause() {
    while(isPaused) {
        await new Promise(resolve => requestAnimationFrame(resolve));
    }
}

// 修改后的 delay 函数（保持原功能）
function delay() {
    return new Promise(resolve => setTimeout(resolve, animationSpeed));
}

// 初始化图表
function initChart() {
    const container = document.getElementById('chart');
    container.innerHTML = '';

    // 动态计算柱状图宽度
    const barWidth = container.offsetWidth / nums.length;

    nums.forEach((num, i) => {
        const bar = document.createElement('div');
        bar.className = 'bar';
        bar.style.height = Math.abs(num * 20) + 'px'; // 缩小高度
        bar.style.left = (i * barWidth) + 'px';
        bar.style.width = barWidth + 'px';
        bar.textContent = num;
        container.appendChild(bar);
    });

    // 创建指针
    ['i', 'j', 'k'].forEach(label => {
        const pointer = document.createElement('div');
        pointer.className = `pointer ${label}-pointer`;
        pointer.id = `${label}-pointer`;
        pointer.dataset.label = label.toUpperCase();
        container.appendChild(pointer);
    });
}

// 更新指针位置
function updatePointers(i, j, k) {
    const container = document.getElementById('chart');
    const barWidth = container.offsetWidth / nums.length;

    document.getElementById('i-pointer').style.left = (i * barWidth) + 'px';
    document.getElementById('j-pointer').style.left = (j * barWidth) + 'px';
    document.getElementById('k-pointer').style.left = (k * barWidth) + 'px';
}



// 辅助函数
function delay() {
    return new Promise(resolve => setTimeout(resolve, animationSpeed));
}

function updateStatus(text) {
    document.getElementById('status').textContent = text;
}

function showSolution(solution) {
    const list = document.getElementById('solution-list');
    const li = document.createElement('li');
    li.textContent = JSON.stringify(solution);
    list.appendChild(li);
    document.getElementById('count').textContent = solutions.length;
}

function highlightBars(i, j, k) {
    const bars = document.getElementsByClassName('bar');
    bars[i].style.background = '#ffd700';
    bars[j].style.background = '#ffd700';
    bars[k].style.background = '#ffd700';
}

// 启动演示
function start() {
    initChart();
    solutions = [];
    document.getElementById('solution-list').innerHTML = '';
    runSteps();
}

// 初始化
initChart();
</script>
</body>
</html>
